<!--
 * @Author: Liz.Zheng
 * @Date: 2021-12-01 16:51:33
 * @LastEditTime: 2023-02-16 10:18:45
 * @LastEditors: 郑亚莉 zhengyali@shequ.life
 * @Description: 新建合同
 * @Motto: Write the code. Change the world.
-->
<template>
  <div
    class="newContract route-page"
    :class="$store.getters.isMobile ? 'isMobile' : ''"
  >
    <section class="header">
      <a-page-header class="hide-back" :title="pageTitle" @back="goBack" />
    </section>
    <section class="content" ref="newContractContentRef">
      <!-- <a-spin :spinning="loading"> -->
      <a-steps
        :current="currentStep"
        v-if="!$store.getters.isMobile"
        size="small"
        type="navigation"
      >
        <a-step title="基本信息" />
        <a-step title="费用条款" />
        <a-step title="合同文本" />
        <a-step :title="isChangeContract ? '退租结算' : '费用结算'" v-if="isChangeContract || isPurposeChangeContract" />
      </a-steps>
      <section
        class="info"
        :style="{ width: $store.getters.isMobile ? '1200px' : undefined }"
      >
        <!--   基本信息   -->
        <basic-info
          v-show="currentStep == 0"
          :detailDataByPort="detailDataByPort"
          @success="handleValidateSuccess"
          @fail="handleValidateFail"
          @changeTreeLoading="changeTreeLoading"
          @onDefaultFinish="(val) => haveEdit = val"
          @branchid="branchid"
          @changeroomList="changeroomList"
        />

        <!--   条款   -->
        <fee-clause
          v-show="currentStep == 1"
          @success="handleValidateSuccess"
          @fail="handleValidateFail"
        />

        <contract-text
          v-show="currentStep == 2"
          :trigger="submitTrigger"
          @success="saveData"
        />
        <settle-info
          v-show="(isChangeContract || isPurposeChangeContract) && currentStep == 3"
          :changeType="isPurposeChangeContract ? 'purpose_change' : ''"
          :trigger="submitTrigger"
          :changeDetail="changeDetail"
          @success="submitChange"
        />
      </section>
      <!-- </a-spin> -->
    </section>
    <a-space class="cu-footer">
      <a-button
        v-if="currentStep > 0"
        @click="lastStep"
        :key="'previous' + currentStep"
      >
        上一步
      </a-button>
      <template v-if="isChangeContract || isPurposeChangeContract">
        <a-button
          type="primary"
          v-if="currentStep < 3"
          @click="nextStep"
          :loading="loadingType == 'nextStep'"
          :key="'next' + currentStep"
        >
          下一步
        </a-button>
        <a-button
          type="primary"
          v-if="currentStep == 3"
          :loading="loadingType == 'submit5'"
          @click="submit(5)"
          style="margin-left: 8px"
        >
          发起审批
        </a-button>
      </template>
      <template v-else>
        <a-button
          type="primary"
          v-if="currentStep < 2"
          @click="nextStep"
          :loading="loadingType == 'nextStep' || selectTreeLoading"
        >
          下一步
        </a-button>
        <template v-if="currentStep == 2">
          <template v-if="isCostContract">
            <a-button
              type="primary"
              :loading="loadingType == 'submit4'"
              @click="submit(4)"
            >
              创建
            </a-button>
          </template>
          <!-- 意向合同：无保存草稿箱 -->
          <template v-else-if="isPurposeContract || isTransferNormal">
            <a-button
              type="primary"
              :loading="loadingType == 'submit1'"
              @click="submit(1)"
              style="margin-left: 8px"
            >
              保存&发起审批
            </a-button>
          </template>
          <template v-else>
            <a-button
              type="primary"
              :loading="loadingType == 'submit3'"
              @click="submit(3)"
            >
              保存
            </a-button>
            <a-button
              type="primary"
              :loading="loadingType == 'submit1'"
              @click="submit(1)"
              style="margin-left: 8px"
            >
              保存&发起审批
            </a-button>
          </template>
        </template>
      </template>
    </a-space>

    <!--  模拟modal.confirm 原因:在提示时点击一级菜单会触发两次onBeforeRouteLeave 拦截会有问题  -->
    <a-modal :visible="showQuitConfirm" :title="null" :footer="null" :closable="false" :width="420" @cancel="handleLeaveCancel">
      <div class="confirm-content">
        <div class="quit-content">
          <ExclamationCircleOutlined style="color: #faad14;font-size: 22px"/>
          <div class="quit-main">
            <div class="quit-title">确认离开</div>
            <div class="quit-tips">离开后，数据将不会保存</div>
          </div>
        </div>
        <div class="quit-footer">
          <a-row type="flex" justify="end">
            <a-col>
              <a-space>
                <a-button @click.stop="handleLeaveCancel">取消</a-button>
                <a-button type="primary" @click.stop="handleLeaveOk">确认</a-button>
              </a-space>
            </a-col>
          </a-row>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script>
import {computed, defineComponent, ref, nextTick, onBeforeUnmount, reactive, createVNode, watch} from "vue";
import store from "../../../store";
import BasicInfo from "./BasicInfo.vue";
import FeeClause from "./FeeClause.vue";
import ContractText from "./ContractText.vue";
import {onBeforeRouteLeave, useRoute, useRouter} from "vue-router";
import request from "../../../common/utils/request";
import {message, Modal} from "ant-design-vue";
import moment from "moment";
import SettleInfo from "./SettleInfo.vue";
import {ExclamationCircleOutlined, LogoutOutlined} from "@ant-design/icons-vue";
import utils from "@/common/utils/utils";
import _ from 'lodash';

export default defineComponent({
  name: "addContract",
  components: { BasicInfo, FeeClause, ContractText, SettleInfo, ExclamationCircleOutlined },
  setup() {
    const $route = useRoute();
    const $router = useRouter();
    const needQuitConfirm = ref(false);
    const showQuitConfirm = ref(false);
    const haveEdit = ref(false);
    const routerNext = ref(null);
    const detailDataByPort = ref({}); // 从后端拿到的详情数据
    const newContractContentRef = ref(null);

    onBeforeUnmount(() => {
      store.dispatch("ResetAddForm");
      store.dispatch("ClearClauseContent");
      store.dispatch("SetDefaultClause");
      store.dispatch("SetTaxRateMap");
      store.dispatch("ClearPaneCheckedRoom");
      store.dispatch("SetInitClauseType");
    });

    onBeforeRouteLeave( (to, from, next) => {
      routerNext.value = next;
      if (needQuitConfirm.value && !$route.query.id) {
        if (haveEdit.value) {
          // 编辑过
          showQuitConfirm.value = true;
        } else {
          // 没编辑过
          handleLeaveOk();
        }
      } else {
        next();
      }
    });

    const handleLeaveOk = () => {
      setTimeout(() => {
        utils.setStorage("contract_draft_info", '');
      },100)
      routerNext.value && routerNext.value();
    };

    const handleLeaveCancel = () => {
      showQuitConfirm.value = false;
    };

    const isRenewal = computed(
      () => $route.query.editType == "renewal"
    );

    // 是否变更合同
    const isChangeContract = computed(
      () => $route.query.contractEditType == "change"
    );

    // 是否意向变更合同
    const isPurposeChangeContract = computed(
      () => $route.query.contractType == "purposeContractChange"
    );

    // 是否复制合同
    const isCopyContract = computed(
      () => $route.query.contractEditType == "copy"
    );

    const changeDetail = computed(() => {
      if (isChangeContract.value || isPurposeChangeContract.value) {
        return {
          originId: $route.query.id,
          changeContractTime: $route.query.startDate,
        }
      } else {
        return {}
      }
    });

    const renewalDetail = computed(() => {
      if (isRenewal.value) {
        return {
          originId: $route.query.id,
          startDate: $route.query.startDate,
          endDate: $route.query.endDate,
          duration: $route.query.duration,
        }
      } else {
        return {}
      }
    });

    const pageTitle = computed(() => {
      if (isRenewal.value) {
        return "合同续租";
      } else {
        if ($route.query.id) {
          if (isChangeContract.value || isCopyContract.value || isPurposeChangeContract.value) {
            return "创建合同";
          } else {
            return "编辑合同";
          }
        }
        return "创建合同";
      }
    });

    const loadingType = ref("");

    let step = 1;
    const currentStep = computed(() => store.getters.currentStep);

    // 是否成本合同
    const isCostContract = computed(
      () => $route.query.contractType == "costContract"
    );

    const isPurposeContractEdit = computed(
      () => $route.query.contractType == "purposeContractEdit"
    );

    // 是否意向合同 或者 意向合同变更
    const isPurposeContract = computed(
      () => $route.query.contractType == "purposeContract" || isPurposeChangeContract.value || isPurposeContractEdit.value
    );

    // 是否意向合同转正
    const isTransferNormal = computed(
      () => $route.query.editType == "transferNormal"
    );

    const lastStep = () => {
      step--;
      store.dispatch("SetCurrentStep", { step });
    };

    let orgBranchId = 0;
    const branchid = (val) => {
      orgBranchId = val
    }

    let roomList = ref([])
    const changeroomList = (list) => {
      roomList.value = []
      for (let i = 0; i < list.length; i++) {
        if(roomList.value.length == 0){
          roomList.value.push(list[i].extra.build_id)
        }else {
          for (let j = 0; j < roomList.value.length; j++) {
            if(list[i].extra.build_id != roomList.value[j]){
              roomList.value.push(list[i].extra.build_id)
            }
          }
        }
      }
    }

    const nextStep = () => {
      // store.dispatch("SetCurrentStep", { step });

      request
          .post("/org", "/contract/checkBuildProcess", {
            build_id: roomList.value,
            org_branch_id: orgBranchId,
          })
          .then((res) => {
            if (!res.hasProcess) {
              Modal.confirm({
                title: () => "提示",
                content: () =>
                    "该楼宇还未绑定合同审批流程，您需要先为您选择的楼宇绑定审批流程哦~",
                icon: () => createVNode(ExclamationCircleOutlined),
                centered: true,
                okText: () => "前往",
                onOk() {
                  utils.goProcessContract({type: "add"});
                },
                onCancel() {
                  // 关闭当前tab
                  const microId = window.microApp?.appName;
                  window.microApp.forceDispatch({
                    type: "SetMicroPagesDel",
                    info: {
                      microId: microId,
                    },
                  });
                },
              });
            }else {
              loadingType.value = "nextStep";
              // 触发表单验证
              const trigger = store.getters.validateTrigger;
              step = currentStep.value;
              if (!trigger) {
                store.dispatch("SetValidateTrigger").then(() => {
                  if ((isChangeContract.value || isPurposeChangeContract.value) && step == 2) {
                    loadingType.value = "";
                    step++;
                    store.dispatch("SetCurrentStep", { step });
                  } else {
                    step++;
                  }
                });
              }
            }
          });
    };
    const selectTreeLoading = ref(false);
    const changeTreeLoading = (val) => {
      selectTreeLoading.value = val;
    };

    // 表单验证成功回调
    const handleValidateSuccess = (e) => {
      loadingType.value = "";
      store.dispatch("SetCurrentStep", { step });
    };
    // 表单验证失败回调
    const handleValidateFail = (e) => {
      loadingType.value = "";
      store.dispatch("SetValidateTrigger", false);
    };

    // 提交表单
    const submitTrigger = ref(0);
    let submitType = 3;
    const submit = (type) => {
      submitType = type;
      loadingType.value = "submit" + type;
      submitTrigger.value++;
    };

    const clearLocalDraft = () => {
      // 清空本地新增数据的草稿
      needQuitConfirm.value = false;
      if (!$route.query.id) {
        // 新增 - 清空缓存
        setTimeout(() => {
          utils.setStorage("contract_draft_info", '');
        },100)
      }
    };

    const saveData = () => {
      clearLocalDraft();
      const { basicInfo, feeClause, contractText } = store.getters.addFormData;
      let allParams = {
        ...basicInfo,
        ...feeClause,
        ...contractText,
        op_type: submitType,
        needMsg: true,
      };
      let requestMethod = "post";
      let requestUrl = "/contract/main-create";

      // 如果是变更合同，saveData()为下一步
      if (isChangeContract.value || isPurposeChangeContract.value) {
        if (currentStep.value == 2) {
          loadingType.value = "";
        }
      } else {
        //新建意向合同
        if (isPurposeContract.value) {
          requestUrl = "/purpose/createMain";
          allParams.op_type = 5;
          if (isPurposeContractEdit.value) {
            allParams.id = id;
          }
        } else if (id && !isCopyContract.value) {
          // 复制合同时不要id,相当于新建一份不同id的相同合同
          if (isRenewal.value) {
            // 续租
            allParams.original_id = id;
            requestUrl = "/create/contractContinue";
          } else if (isTransferNormal.value) {
            // 意向合同转正(相当于新建合同)
            allParams.original_id = id;
          } else {
            allParams.id = id;
            requestMethod = "put";
            requestUrl = "/create/contractEdit";
          }
        }
        allParams.discount_price = 0;
        let roomIdList = [];
        let villageIdList = [];
        let buildIdList = [];
        if (allParams?.expense_clause?.length) {
          allParams.expense_clause.forEach((v) => {
            allParams.discount_price = utils.countSum([
              Number(v?.report_detail?.receiveDiscount || 0),
              allParams.discount_price,
            ]);
            let roomList = v?.checked_build?.room;
            roomList.forEach((item) => {
              if (!roomIdList.find((roomId) => roomId == item.id)) {
                roomIdList.push(item.id)
              }
              let roomVillageId = item?.extra?.village_id || item?.village_id;
              if (!villageIdList.find((villageId) => villageId == roomVillageId)) {
                villageIdList.push(roomVillageId)
              }
              let roomBuildId = item?.extra?.build_id || item?.build_id;
              if (!buildIdList.find((buildId) => buildId == roomBuildId)) {
                buildIdList.push(roomBuildId)
              }
            })
          });
        }
        console.log(allParams?.build_bind, 'allParams?.build_bind==')
        let roomList = (allParams?.build_bind?.room || []).filter((v) => roomIdList.includes(v.id));
        let buildList = (allParams?.build_bind?.build || []).filter((v) => buildIdList.includes(v.id));
        if (!villageIdList?.length) {
          allParams.build_bind.village = {}
        }
        allParams.build_bind.room = roomList;
        allParams.build_bind.build = buildList;
        console.log("allParams", allParams);
        request[requestMethod]("/org", requestUrl, allParams)
          .then((res) => {
            message.success(res.msg || "保存成功");
            // 更新合同列表
            let refreshType = 'SetContractListInit';
            if (submitType == 3) {
              // 保存为草稿
              refreshType = 'SetDraftContractListInit';
            }
            store.dispatch(refreshType, true).then(() => {
              // 如果是复制合同，跳到合同列表
              goBack();
            });
          })
          .finally(() => {
            loadingType.value = "";
          });
      }
    };

    const submitChange = () => {
      clearLocalDraft();
      if ((isChangeContract.value || isPurposeChangeContract.value) && currentStep.value == 3) {
        const { basicInfo, feeClause, contractText, settleInfo } =
          store.getters.addFormData;
        let allParams = {
          createMain: {
            ...basicInfo,
            ...feeClause,
            ...contractText,
            // op_type: submitType, //变更合同不需要传op_type
          },
          ...settleInfo,
          needMsg: true,
        };
        let requestMethod = "post";
        let requestUrl = "/contract/main-create";
        if (id) {
          allParams.original_id = id;
          requestUrl = "/contract/change/create";
          if (isPurposeChangeContract.value) {
            requestUrl = "/contract/change/addPurposeContract";
          }
          const changeData = changeDetail.value;
          if (changeData && changeData.changeContractTime) {
            allParams.retreat_date = moment(changeData.changeContractTime)
              .subtract(1, "days")
              .format("YYYY-MM-DD");
          }
        }
        console.log("allParams isChangeContract", allParams);
        allParams.createMain.discount_price = 0;

        let roomIdList = [];
        let villageIdList = [];
        let buildIdList = [];

        if (allParams.createMain?.expense_clause?.length) {
          allParams.createMain.expense_clause.forEach((v) => {
            allParams.createMain.discount_price = utils.countSum([
              Number(v?.report_detail?.receiveDiscount || 0),
              allParams.createMain.discount_price,
            ]);
            let roomList = v?.checked_build?.room;
            roomList.forEach((item) => {
              if (!roomIdList.find((roomId) => roomId == item.id)) {
                roomIdList.push(item.id)
              }
              let roomVillageId = item?.extra?.village_id || item?.village_id;
              if (!villageIdList.find((villageId) => villageId == roomVillageId)) {
                villageIdList.push(roomVillageId)
              }
              let roomBuildId = item?.extra?.build_id || item?.build_id;
              if (!buildIdList.find((buildId) => buildId == roomBuildId)) {
                buildIdList.push(roomBuildId)
              }
            })
          });
        }
        let roomList = (allParams?.createMain?.build_bind?.room || []).filter((v) => roomIdList.includes(v.id));
        let buildList = (allParams?.createMain?.build_bind?.build || []).filter((v) => buildIdList.includes(v.id));
        if (!villageIdList?.length) {
          allParams.createMain.build_bind.village = {}
        }
        allParams.createMain.build_bind.room = roomList;
        allParams.createMain.build_bind.build = buildList;

        request[requestMethod]("/org", requestUrl, allParams)
          .then((res) => {
            message.success(res.msg || "变更成功");
            goBack();
          })
          .finally(() => {
            loadingType.value = "";
          });
      }
    };

    const getDetail = (originId) => {
      request
        .get("/org", "/create/contractInfo", { id: originId || id })
        .then((res) => {
          const renewalData = renewalDetail.value;
          const changeData = changeDetail.value;
          if (isRenewal.value) {
            res.clauseData.forEach((item) => {
              if (item.multiple_clause && item.multiple_clause.length) {
                item.multiple_clause.forEach((item2) => {
                  item2.charge_begintime = renewalData.startDate;
                  item2.charge_endtime = renewalData.endDate;
                });
              }
            });
          }
          console.log(res.clauseData);
          detailDataByPort.value = _.cloneDeep(res);
          // 渲染合同信息时，检查租客信息是否失效
          let owner_id = res.owner_id;
          let owner_info = res.owner_info;
          if (owner_id) {
            request
              .get("/org", "/bill/getOwnerAccount", {
                owner_id: owner_id,
              })
              .then((res) => {
                // 如果没有租客数据，则清空原租客信息
                if (!res.ownerData.id) {
                  owner_id = null;
                  owner_info = {};
                }
              })
              .finally(() => {
                let basicInfo = {
                    template_id: isRenewal.value
                      ? undefined
                      : res.template_id,
                    contract_number:
                      isRenewal.value || isChangeContract.value || isPurposeChangeContract.value
                        ? ""
                        : res.contract_number,
                    followup_uid: isChangeContract.value || isPurposeChangeContract.value
                      ? store.getters.userInfo.uid
                      : res.followup_uid,
                    sign_time:
                      isRenewal.value || isChangeContract.value || isPurposeChangeContract.value
                        ? moment().format("YYYY-MM-DD")
                        : res.sign_time,
                    unit_price_point: res.unit_price_point,
                    calculate_accuracy: res.calculate_accuracy,
                    calculate_order: res.calculate_order,
                    receivable_round: res.receivable_round,
                    owner_id: owner_id,
                    owner_info: owner_info,
                    late_fee: res.late_fee || {
                      startDay: "",
                      ratio: "",
                      toplimit: "",
                    },
                    lease_starttime: isRenewal.value
                      ? renewalData.startDate
                      : (isChangeContract.value || isPurposeChangeContract.value)
                        ? changeData.changeContractTime
                        : res.lease_starttime,
                    lease_endtime: isRenewal.value
                      ? renewalData.endDate
                      : res.lease_endtime,
                    lease_square: res.lease_square,
                    property_square: res.property_square,
                    build_bind: res.build_bind,
                    contract_tag: res.contract_tag
                      ? res.contract_tag.split(",")
                      : [],
                    room_rent: res.room_rent,
                    extra_field: res.extra_field,
                    org_branch_id: res.org_branch_id,
                    is_branch_account: res.is_branch_account,
                  };
                if (isPurposeChangeContract.value || isPurposeContractEdit.value) {
                  // 意向合同变更 回显
                  basicInfo.purpose_receive_price = res.purpose_receive_price;
                  basicInfo.purpose_receive_time = res.purpose_receive_time;
                  basicInfo.purpose_unlock_time = res.purpose_unlock_time;
                  basicInfo.purpose_pay_method = res.purpose_pay_method;
                  basicInfo.purpose_is_return = res.purpose_is_return;
                }
                store.dispatch("SetAllAddFormData", {
                    feeClause: {
                      expense_clause: res.clauseData,
                    },
                    contractText: {
                      object_id: res.object_id,
                      apply_contract: res.apply_contract,
                      apply_template_id: res.apply_template_id,
                    },
                    basicInfo: basicInfo,
                  })
                  .then(() => {
                    store.dispatch("SetEditContractId", id || originId);
                  });
              });
          }
        });
    };

    const goBack = () => {
      if (window.__MICRO_APP_ENVIRONMENT__) {
        window.microApp.forceDispatch({
          type: "SetMicroPages",
          microInfo: {
            microId: `org_contract_list`,
            app: 'org',
            name: '合同列表',
            url: `/contract/contractList`,
          }
        })
        const microId = window.microApp?.appName;
        setTimeout(() => {
          window.microApp.forceDispatch({
            type: "SetMicroPagesDel",
            info: {
              microId: microId,
            },
          });
        }, 0);
      }
    };

    let id = 0;
    const init = () => {
      // 变更合同时
      const changeData = changeDetail.value;
      // 编辑合同时
      id = $route.query.id;

      if (changeData && changeData.originId) {
        getDetail(changeData.originId);
      } else if (id) {
        getDetail();
      }

      if (!id) {
        needQuitConfirm.value = true;
        let draftInfo = utils.getStorage("contract_draft_info");
        if (!draftInfo) return;
        draftInfo = JSON.parse(draftInfo);
        if(!_.isEmpty(draftInfo)) {
          Modal.confirm({
            title: () => "是否打开上次编辑的草稿",
            content: () => `最近保存于${draftInfo.lastTime}`,
            icon: () => createVNode(ExclamationCircleOutlined),
            centered: true,
            okText: () => "打开草稿",
            cancelText: '放弃草稿',
            onOk() {
              // 打开草稿
              store.dispatch("SetContractAddDraft", draftInfo);
              utils.setStorage("contract_draft_info", '');
              store.dispatch("SetUseDraft", true);
            },
            onCancel() {
              // 放弃草稿
              utils.setStorage("contract_draft_info", '');
              store.dispatch("SetUseDraft", false);
            },
          });
        }
      }
    };

    init();

    watch(
      () => currentStep.value,
      (val) => {
        nextTick(() => {
          newContractContentRef.value?.scrollTo(0,0);
        })
      },
    );

    return {
      pageTitle,
      currentStep,
      loadingType,
      submitTrigger,
      isRenewal,
      newContractContentRef,
      lastStep,
      nextStep,
      handleValidateSuccess,
      handleValidateFail,
      submit,
      saveData,
      goBack,
      isCostContract,
      isChangeContract,
      isPurposeChangeContract,
      submitChange,
      isPurposeContract,
      isTransferNormal,
      changeTreeLoading,
      selectTreeLoading,
      showQuitConfirm,
      handleLeaveCancel,
      handleLeaveOk,
      haveEdit,
      detailDataByPort,
      branchid,
      changeroomList,
      orgBranchId,
      changeDetail,
    };
  },
});
</script>

<style lang="less" scoped>
.newContract {
  height: 100%;
  display: flex;
  flex-direction: column;
  .header {
    height: 50px;
    &:deep(.ant-page-header) {
      padding: 10px 20px;
    }
  }
  .content {
    flex: 1;
    padding: 10px;
    margin: 10px;
    max-height: calc(~"100%- 160px");
    overflow-y: auto;
    background: #ffffff;
    .info {
      padding: 10px;
    }
  }
  .cu-footer {
    height: 50px;
    display: flex;
    justify-content: flex-end;
    // background: #f7f7f7;
    align-items: center;
    padding: 0 20px;
    box-sizing: border-box;
  }
  &.isMobile {
    :deep(.ant-page-header-back) {
      display: none;
    }
  }
}
.quit-content {
  display: flex;
  margin-bottom: 24px;
}
.confirm-content {
  padding: 20px 20px 10px 20px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.quit-main {
  margin-left: 10px;
  .quit-title {
    font-size: 15px;
    font-weight: bold;
    margin-bottom: 6px;
  }
}
.hide-back {
  :deep(.ant-page-header-back) {
    display: none;
  }
}

</style>
